import { Injectable } from '@angular/core';
import { AppConfig } from "../config";
import { Headers, Http } from '@angular/http';
import { MenuShortcut } from "../entity/menu_shortcut.model";
import { InterceptorService } from '../service/interceptor/interceptor-service';

/**
 * 快捷菜单
 * 固定菜单
 * 
 * @export
 * @class MenuShortcutService
 */
@Injectable()
export class MenuShortcutService {
    private readonly param = "sysMenuShortCuts";
    private get url(): string {
        return `${AppConfig.APP_RESTFUL}/${this.param}`;
    }

    constructor(private http: InterceptorService) { }


    //新增
    create(menuShortcut: MenuShortcut): Promise<any> {
        // const Url = `http://192.168.15.150:8585/webapi/v1/sysRoles`
        return this.http.post(this.url, JSON.stringify(menuShortcut))
            .toPromise()
            .then(res => {
                try {
                    let result = res.json();
                    switch (result.code) {
                        case "200":
                            return result.code as MenuShortcut;
                        case "-1":
                            throw new Error(result.message);
                    }
                }
                catch (error) {
                    this.handleError(error);
                }
            })
            .catch(this.handleError);
    }
    //更新
    update(menuShortcut: MenuShortcut): Promise<MenuShortcut> {
        const url = `${this.url}`;
        return this.http.put(url, JSON.stringify(menuShortcut))
            .toPromise()
            .then(() => menuShortcut)
            .catch(this.handleError);
    }
    //删除、批量删除
    batchDelete(valueIds: number[]): Promise<boolean> {
        const url = `${this.url}?items=${valueIds}`;
        // const url = `http://192.168.15.150:8585/webapi/v1/sysRoles?items=${valueIds}`;
        return this.http.delete(url)
            .toPromise()
            .then(response => {
                try {
                    let result = response.json();
                    switch (result.code) {
                        case "200":
                            return true;
                        case "-1":
                            throw new Error(result.message);
                    }
                }
                catch (error) {
                    throw error;
                }

            })
            .catch(this.handleError);
    }

    //通过角色Id获取固定菜单列表
    getMenuShortCutsByroleId(roleId: number): Promise<MenuShortcut[]> {
        // const url = `http://192.168.15.150:8585/webapi/v1/sysMenuShortCuts/`;
        return this.http.get(`${this.url}/roleId/${roleId}`)
            .toPromise()
            .then(response => response.json().data as MenuShortcut[])
            .catch(this.handleError);
    }

    private handleError(error: any): Promise<any> {
        return Promise.reject(error.message || error);
    }
}


// WEBPACK FOOTER //
// ./src/app/service/menu_shortcut.service.ts